import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store/index'

import login from '@/views/login/login.vue'
import register from '@/views/register/register.vue'
import index from '@/views/layout/index.vue'
import home from '@/views/Home/HomeIndex.vue'
import userInfo from '@/views/user/userInfo.vue'
import userAvatar from '@/views/user/userAvatar.vue'
import userPwd from '@/views/user/userPwd.vue'
import article from '@/views/article/artCate.vue'
import artList from '@/views/article/artList.vue'
Vue.use(VueRouter)
const routes = [
  // 注册页
  {
    path: '/reg',
    component: register
  },
  // 主页面
  {
    path: '/',
    component: index,
    redirect: '/home',
    children: [
      // 首页
      {
        path: '/home',
        component: home
      },
      // 文章管理
      // 文章分类
      {
        path: '/art-cate',
        component: article
      },
      // 文章列表
      {
        path: '/art-list',
        component: artList
      },
      // 个人中心
      {
        path: 'user-info',
        component: userInfo
      },
      // 更换头像
      {
        path: 'user-avatar',
        component: userAvatar
      },
      // 更换密码
      {
        path: 'user-pwd',
        component: userPwd
      }
    ]
  },
  // 登录页
  {
    path: '/login',
    component: login
  }
]
const router = new VueRouter({
  routes
})

const whiteList = ['/login', '/reg'] // 白名单
// 路由跳转时调用
router.beforeEach((to, from, next) => {
  // 判断是否有token，有token才能获取用户信息
  const token = store.state.token
  // 有token说明登陆了，才放行
  if (token) {
    // 没有用户名的时候才去请求用户基本数据
    if (!store.state.userInfo.username) {
      store.dispatch('getUSerInfo')
    }
    next()
  } else {
    // 数组.includes(值)，作用：判断值是否在数组中出现过，出现返回true
    if (whiteList.includes(to.path)) {
      next()
    }
    // 未登录呢强制跳到/login
    // 如果没有上面的if判断，next先强制跳到login，但会再次触发前置守卫，
    // 让后判断又会跳到next('/login'),一直反复下去报错
    next('/login')
  }
})
export default router
